package com.lu.common.controller;

import ch.qos.logback.core.db.dialect.DBUtil;
import com.lu.common.domain.ConfigurationDO;
import com.lu.common.domain.DbUrl;
import com.lu.common.service.impl.GeneratorServiceImpl;
import com.lu.common.utils.DBTools;
import com.lu.common.utils.GenUtils;
import com.lu.common.utils.R;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/common/generator")
@Controller
public class GeneratorController {

    String prefix = "common/generator";

    public DbUrl getDb(HttpSession session) throws Exception{
        String dbDriver=(String)session.getAttribute("dbDriver");
        String dbIp=(String)session.getAttribute("dbIp");
        String dbPort=(String)session.getAttribute("dbPort");
        String dbName=(String)session.getAttribute("dbName");
        String dbUsername=(String)session.getAttribute("dbUsername");
        String dbPassword=(String)session.getAttribute("dbPassword");
        String dbUrl="jdbc:mysql://"+dbIp+":"+dbPort+"/"
                +dbName+"?useUnicode=true&characterEncoding=utf8";
        DbUrl db=new DbUrl();
        db.setDriver(dbDriver);
        db.setUrl(dbUrl);
        db.setUsername(dbUsername);
        db.setPassword(dbPassword);
        return db;
    }

    @GetMapping("/list")
    @ResponseBody
    public Object index2(HttpSession session){
        R r = new R();
        GeneratorServiceImpl generatorService=new GeneratorServiceImpl();
        List<Map<String, Object>> lists= null;
        try {
            lists = generatorService.list(getDb(session));
            if(lists==null){
                r.put("res",-1);
                return r;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lists;
    }

    @RequestMapping("/code/{tableName}")
    public void code(HttpServletRequest request, HttpServletResponse response,
                     @PathVariable("tableName") String tableName,HttpSession session) throws IOException {
        String[] tableNames = new String[] { tableName };
        GeneratorServiceImpl generatorService=new GeneratorServiceImpl();
        byte[] data = new byte[0];
        try {
            data = generatorService.generatorCode(tableNames,getDb(session),getConfigurationDO(session));
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"lu.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

    @RequestMapping("/batchCode")
    public void batchCode(HttpServletRequest request, HttpServletResponse response, String tables,HttpSession session) throws IOException {
//        String[] tableNames = new String[] {};
        try {
            String[] tableNames=tables.split(",");
//        for(int i=0;i<lists.size();i++){
//            tableNames[i]=lists.get(0);
//        }
//        tableNames = JSON.parseArray(tables).toArray(tableNames);
            GeneratorServiceImpl generatorService=new GeneratorServiceImpl();
            byte[] data = new byte[0];
            try {
                data = generatorService.generatorCode(tableNames,getDb(session),getConfigurationDO(session));
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"lu.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");

            IOUtils.write(data, response.getOutputStream());
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }

    /**
     *
     * @param model
     * @return
     */
    @GetMapping("/edit")
    public String edit(Model model,HttpSession session) {
//        ConfigurationDO conf = GenUtils.getConfig();
        String author=(String)session.getAttribute("author");
        String email=(String)session.getAttribute("email");
        String packages=(String)session.getAttribute("packages");
        String autoRemovePre=(String)session.getAttribute("autoRemovePre");
        String tablePrefix=(String)session.getAttribute("tablePrefix");

        if(author==null){
            author="chglee";
            session.setAttribute("author",author);
        }
        if(email==null){
            email="1992lcg@163.com";
            session.setAttribute("email",email);
        }
        if(packages==null){
            packages="com.uu.system";
            session.setAttribute("packages",packages);
        }
        if(autoRemovePre==null){
            autoRemovePre="false";
            session.setAttribute("autoRemovePre",autoRemovePre);
        }if(tablePrefix==null){
            tablePrefix="sys_";
            session.setAttribute("tablePrefix",tablePrefix);
        }

        Map<String, Object> property = new HashMap<>(16);
        property.put("author",author);
        property.put("email",email);
        property.put("packages",packages);
        property.put("autoRemovePre",autoRemovePre);
        property.put("tablePrefix",tablePrefix);
        model.addAttribute("property", property);
        return prefix + "/edit";
    }

    @ResponseBody
    @GetMapping("/update")
    R update(HttpSession session,@RequestParam String author,@RequestParam String email,@RequestParam String packages,@RequestParam String autoRemovePre,@RequestParam String tablePrefix) {
        try {
            session.removeAttribute("author");
            session.removeAttribute("email");
            session.removeAttribute("packages");
            session.removeAttribute("autoRemovePre");
            session.removeAttribute("tablePrefix");

            session.setAttribute("author",author);
            session.setAttribute("email",email);
            session.setAttribute("packages",packages);
            session.setAttribute("autoRemovePre",autoRemovePre);
            session.setAttribute("tablePrefix",tablePrefix);

        } catch (Exception e) {
            return R.error("保存配置文件出错");
        }
        return R.ok();
    }

    public ConfigurationDO getConfigurationDO(HttpSession session){
        String author=(String)session.getAttribute("author");
        String email=(String)session.getAttribute("email");
        String packages=(String)session.getAttribute("packages");
        String autoRemovePre=(String)session.getAttribute("autoRemovePre");
        String tablePrefix=(String)session.getAttribute("tablePrefix");

        if(author==null){
            author="chglee";
            session.setAttribute("author",author);
        }
        if(email==null){
            email="1992lcg@163.com";
            session.setAttribute("email",email);
        }
        if(packages==null){
            packages="com.uu.system";
            session.setAttribute("packages",packages);
        }
        if(autoRemovePre==null){
            autoRemovePre="false";
            session.setAttribute("autoRemovePre",autoRemovePre);
        }if(tablePrefix==null){
            tablePrefix="sys_";
            session.setAttribute("tablePrefix",tablePrefix);
        }

        ConfigurationDO conf=new ConfigurationDO();
        conf.setAuthor(author);
        conf.setEmail(email);
        conf.setPackages(packages);
        conf.setAutoRemovePre(autoRemovePre);
        conf.setTablePrefix(tablePrefix);
        return conf;
    }

    /**
     * spring.datasource.url=jdbc:mysql://localhost:3306/bootdo?useUnicode=true&characterEncoding=utf8
     spring.datasource.username=root
     spring.datasource.password=111111
     spring.datasource.driver-class-name=com.mysql.jdbc.Driver
     * @param model
     * @return
     */
    @GetMapping("/editDb")
    public String editDb(Model model,HttpSession session) {
        Map<String, Object> property = new HashMap<>(16);
        //jdbc:mysql://localhost:3306/bootdo?useUnicode=true&characterEncoding=utf8
        if(session.getAttribute("dbDriver")==null){
            property.put("dbDriverClassName","com.mysql.jdbc.Driver");
            property.put("dbIp","localhost");
            property.put("dbPort","3306");
            property.put("dbName","dbName");
            property.put("dbUsername", "root");
            property.put("dbPassword", "111111");
        }else{
            property.put("dbDriverClassName",session.getAttribute("dbDriver"));
            property.put("dbIp",session.getAttribute("dbIp"));
            property.put("dbPort",session.getAttribute("dbPort"));
            property.put("dbName",session.getAttribute("dbName"));
            property.put("dbUsername",session.getAttribute("dbUsername"));
            property.put("dbPassword",session.getAttribute("dbPassword"));
        }
        model.addAttribute("propertyDb", property);
        return prefix + "/editDb";
    }

//    @ResponseBody
//    @PostMapping("/updateDb")
//    R updateDb(@RequestParam Map<String, Object> map) {
//        try {
//            if
//            String dbUrl="jdbc:mysql://"+map.get("dbIp")+":"+map.get("dbPort")+"/"
//                    +map.get("dbName")+"?useUnicode=true&characterEncoding=utf8";
//            String dbDriver="com.mysql.jdbc.Driver";
//            db=new DbUrl(dbDriver,dbUrl,map.get("dbUsername").toString(),map.get("dbPassword").toString());
//        } catch (Exception e) {
//            return R.error("保存配置文件出错");
//        }
//        return R.ok();
//    }

    @ResponseBody
    @GetMapping("/updateDb")
    R updateDb(@RequestParam String dbIp, @RequestParam String dbPort,
               @RequestParam String dbName, @RequestParam String dbUsername, @RequestParam String dbPassword, HttpSession session) {
        try {
            //清楚原先的
            session.removeAttribute("dbDriver");
            session.removeAttribute("dbIp");
            session.removeAttribute("dbPort");
            session.removeAttribute("dbName");
            session.removeAttribute("dbUsername");
            session.removeAttribute("dbPassword");

            String dbDriver="com.mysql.jdbc.Driver";

            //更新现有的
            session.setAttribute("dbDriver",dbDriver);
            session.setAttribute("dbIp",dbIp);
            session.setAttribute("dbPort",dbPort);
            session.setAttribute("dbName",dbName);
            session.setAttribute("dbUsername",dbUsername);
            session.setAttribute("dbPassword",dbPassword);

            if(checkDb(session)==null){
                return R.error("数据库连接失败,请检查数据库配置");
            }
        } catch (Exception e) {
            return R.error("保存配置文件出错");
        }
        return R.ok();
    }

    public Object checkDb(HttpSession session) throws Exception{
        String dbDriver=(String)session.getAttribute("dbDriver");
        String dbIp=(String)session.getAttribute("dbIp");
        String dbPort=(String)session.getAttribute("dbPort");
        String dbName=(String)session.getAttribute("dbName");
        String dbUsername=(String)session.getAttribute("dbUsername");
        String dbPassword=(String)session.getAttribute("dbPassword");
        String dbUrl="jdbc:mysql://"+dbIp+":"+dbPort+"/"
                +dbName+"?useUnicode=true&characterEncoding=utf8";
        DbUrl db=new DbUrl();
        db.setDriver(dbDriver);
        db.setUrl(dbUrl);
        db.setUsername(dbUsername);
        db.setPassword(dbPassword);
        DBTools dbTools=new DBTools(db);
        return  dbTools.getCon();
    }

}
